package com.agw.crm.settings.web.controller;

import com.agw.crm.settings.domain.User;
import com.agw.crm.settings.service.UserService;
import com.agw.crm.settings.service.impl.UserServiceImpl;
import com.agw.crm.utils.MD5Util;
import com.agw.crm.utils.PrintJson;
import com.agw.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UserController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求路径，根据请求路径调方法
        String path = request.getServletPath();

        if ("/settings/user/login.do".equals(path)){
            login(request,response);
        }else if ("/settings/user/xxx.do".equals(path)){
            //xxx(request,response);
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) {
        //获取参数信息
        String loginAct = request.getParameter("loginAct");
        String loginPwd = request.getParameter("loginPwd");
        loginPwd = MD5Util.getMD5(loginPwd);
        //获取浏览器端的ip地址
        String ip = request.getRemoteAddr();
        System.out.println("................." + ip);
        System.out.println("................." + ip);

        //使用代理对象，在业务层进行业务的处理
        UserService us = (UserService) ServiceFactory.getService(new UserServiceImpl());

        try {
            //调用接口方法，进行业务处理，传入上面的三个参数
            User user = us.login(loginAct,loginPwd,ip);//这里可能会出异常，所以要用try catch处理
            //将查询返回数据写入session对象中
            request.getSession().setAttribute("user",user);
            //能到这，说明登录成功,调用方法，向前端返回信息
            PrintJson.printJsonFlag(response,true);
        } catch (Exception e) {
            e.printStackTrace();
            //到这里说明登录失败，出现异常了
            String msg = e.getMessage();

            //调用方法，向前端返回相应信息，不经常使用的使用map
            Map<String ,Object> map = new HashMap<>();
            map.put("success",false);
            map.put("msg",msg);

            PrintJson.printJsonObj(response,map);

        }

    }
}
